package com.renwei.yunlong.activity.work;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.adapter.TablayoutAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.bean.WorkInformationBean;
import com.renwei.yunlong.bean.WorkSpareBean;
import com.renwei.yunlong.event.WorkPageRefreshEvent;
import com.renwei.yunlong.event.WorkPageStateRefreseEvent;
import com.renwei.yunlong.fragment.BaseAnnexFragment;
import com.renwei.yunlong.fragment.BaseHistoryFragment;
import com.renwei.yunlong.fragment.WorkDetailsFragment;
import com.renwei.yunlong.fragment.WorkRecordingFragment;
import com.renwei.yunlong.fragment.WorkRelatedFragment;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.view.SetList;
import com.renwei.yunlong.view.SimpleOptionView;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import github.opensource.dialog.prompt.PromptButton;
import github.opensource.dialog.prompt.PromptButtonListener;
import github.opensource.dialog.prompt.PromptDialog;


/**
 * 工单信息--页面
 * <p>
 * Created by Administrator on 2017/8/28.
 */

public class WorkInformationActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener, PromptButtonListener {

    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.tab_layout)
    TabLayout tabLayout;
    @Bind(R.id.v_pager)
    ViewPager vPager;
    @Bind(R.id.btn_work)
    Button btnWork;
    @Bind(R.id.rl_button)
    RelativeLayout rlButton;
    private TablayoutAdapter adapter;
    private String requestId = "";
    private boolean isLook = false;

    private final String POWER_ZHIPAIGEI = "指派给";
    private final String POWER_JIEDAN = "接单";
    private final String POWER_QUXIANCHANG = "去现场";
    private final String POWER_FEIXIANCHANG = "非现场";
    private final String POWER_ZHUANHUI = "转回";
    private final String POWER_QIDONG = "启动";
    private final String POWER_GUAQI = "挂起";
    private final String POWER_CHUFA = "出发";
    private final String POWER_DAODA = "到达";
    private final String POWER_BIANGENGSHUXING = "变更属性";
    private final String POWER_BEIJIANSHENQING = "备件申请";
    private final String POWER_CHULI = "处理";
    private final String POWER_QUEREN = "确认";
    private final String POWER_GUANBI = "关闭";
    private final String POWER_QUXIAO = "取消";
    private final String POWER_TOUSU = "投诉";

    private SetList<String> powerSet;
    private PromptDialog promptDialog;
    private WorkInformationBean workInformationBean;
    private String outsourceFlag;
    private String newRequestId;
    private boolean isFinish; // EventBus
    private PromptButton[] buttons;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_information);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        requestId = getIntent().getStringExtra("requestId");
        newRequestId = getIntent().getStringExtra("newRequestId");
        outsourceFlag = getIntent().getStringExtra("outsourceFlag");
        isLook = getIntent().getBooleanExtra("isLook", false);
        initView();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initView() {
        simpleTileView.setTitle("工单信息");
        // 弹框
        promptDialog = new PromptDialog(this);

        //页面，数据源
        List<Fragment> list = new ArrayList<>();
        String id;
        if ("1".equals(companyType) && "1".equals(outsourceFlag)) {  // 业主 外协单
            id = newRequestId;
        } else {
            id = requestId;
        }
        list.add(new WorkDetailsFragment(id, outsourceFlag, true));
        list.add(new WorkRecordingFragment(id, outsourceFlag));
        list.add(new BaseAnnexFragment(id, "work", outsourceFlag));
        list.add(new BaseHistoryFragment(id, "work", outsourceFlag));
        list.add(new WorkRelatedFragment(id, outsourceFlag));

        String[] titles = {"详情", "记录", "附件", "历史", "相关"};
        //ViewPager的适配器
        adapter = new TablayoutAdapter(getSupportFragmentManager(), list, titles);
        vPager.setAdapter(adapter);
        vPager.setOffscreenPageLimit(4);
        //绑定
        tabLayout.setupWithViewPager(vPager);

        btnWork.setOnClickListener(this);
    }

    private void initData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("requestId", requestId);
        ServiceRequestManager.getManager().getWorkDetail(this, "", false, JsonMapUtil.mapToJson(map), this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_work:
                if (powerSet.size() != 0) {
                    if (buttons == null) {
                        buttons = new PromptButton[powerSet.size() + 1];
                        buttons[0] = new PromptButton("取消", null);
                        int i = 0;
                        Collections.reverse(powerSet);
                        for (String s : powerSet) {
                            i++;
                            buttons[i] = new PromptButton(s, this);
                        }
                    }
                    promptDialog.showBottomAlert("", true, buttons);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 当前刷新
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefresh(WorkPageRefreshEvent event) {
        isFinish = event.isFinish;
        powerSet.clear();
        initData();
    }

    @Override
    public void onClick(PromptButton button) {
        switch (button.getText()) {
            case POWER_ZHIPAIGEI:
                WorkAssignedActivity.OpenActivity(this, requestId, outsourceFlag);
                break;
            case POWER_JIEDAN:
                WorkDateSelecterActivity.OpenActivity(this, requestId, workInformationBean.getRows().getEventId() + "", "接受");
                break;
            case POWER_QUXIANCHANG:
                WorkDateSelecterActivity.OpenActivity(this, requestId, workInformationBean.getRows().getEventId() + "", "去现场");
                break;
            case POWER_FEIXIANCHANG:
                WorkDateSelecterActivity.OpenActivity(this, requestId, workInformationBean.getRows().getEventId() + "", "非现场");
                break;
            case POWER_ZHUANHUI:
                WorkCloseActivity.OpenActivity(this, requestId, workInformationBean.getRows().getEventId() + "",
                        workInformationBean.getRows().getSendUserName(), "转回");
                break;
            case POWER_QIDONG:
                WorkCancelActivity.OpenActivity(this, requestId, workInformationBean.getRows().getEventId() + "", "启动");
                break;
            case POWER_GUAQI:
                WorkCancelActivity.OpenActivity(this, requestId, workInformationBean.getRows().getEventId() + "", "挂起");
                break;
            case POWER_CHUFA:                                 // 出发 OK
//                chufaHttp();
                WorkMapActivity.OpenActivity(this, requestId, workInformationBean.getRows().getEventId() + "", WorkMapActivity.FROM_CHUFA); // 出发  OK
                break;
            case POWER_BIANGENGSHUXING:  // 变更属性 无
//                startActivity(new Intent(WorkInformationActivity.this, WorkAlterationActivity.class));
                break;
            case POWER_BEIJIANSHENQING:  // 备件申请  ok
                ServiceRequestManager.getManager().getSpareState(this, requestId, this);
                break;
            case POWER_CHULI:
                WorkHandlerActivity.OpenActivity(this, requestId, workInformationBean.getRows().getEventId() + "",
                        workInformationBean.getRows().getOwnerCode(), workInformationBean.getRows().getTreatment());
                break;
            case POWER_QUEREN:
                WorkConfirmActivity.OpenActivity(this, requestId);
                break;
            case POWER_GUANBI:
                WorkCloseActivity.OpenActivity(this, requestId, workInformationBean.getRows().getEventId() + ""
                        , workInformationBean.getRows().getSendUserName(), "关闭");
                break;
            case POWER_QUXIAO:
                WorkCancelActivity.OpenActivity(this, requestId, workInformationBean.getRows().getEventId() + "", "取消");
                break;
            case POWER_TOUSU:
                WorkComplaintsActivity.OpenActivity(this, requestId);
                break;
            case POWER_DAODA:
                WorkMapActivity.OpenActivity(this, requestId, workInformationBean.getRows().getEventId() + "", WorkMapActivity.FROM_DAODA); // 到达OK
                break;
            default:
                break;
        }
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1:  // 权限 初始化
                powerSet = new SetList<>();
                buttons = null;
                workInformationBean = new Gson().fromJson(result, WorkInformationBean.class);
                if (workInformationBean.getMessage().getCode() == 200) {
                    initPower();
                    if (isFinish) {
                        finish();
                    }
                } else {
                    showCenterInfoMsg(workInformationBean.getMessage().getMessage());
                }
                break;
            case 2:  // 工单 出发
                EventBus.getDefault().post(new WorkPageRefreshEvent());
                CommonBean bean = new Gson().fromJson(result, CommonBean.class);
                if (bean.getMessage().getCode() == 200) {
                    showCenterSuccessMsg(bean.getMessage().getMessage());
                } else {
                    showCenterInfoMsg(bean.getMessage().getMessage());
                }
                break;
            case 3: //备件申请
                WorkSpareBean workSpareBean = new Gson().fromJson(result, WorkSpareBean.class);
                setSpareState(workSpareBean);
                break;
            default:
                break;
        }
    }

    private void setSpareState(WorkSpareBean workSpareBean) {
        if (workSpareBean.getTotal() == 0) {
            WorkSpareActivity.OpenActivity(this, WorkInformationActivity.this.requestId
                    , workInformationBean.getRows().getEventId() + "", workInformationBean.getRows().getContractId() + "", workSpareBean);
        } else if (workSpareBean.getTotal() == 1) {
            showCenterInfoMsg("此工单服务对象正在备件申请流程中或不可以备件申请！");
        }
    }

    private void initPower() {
        boolean isNowState = false;
        if ("1".equals(companyType)) {
            if ("0".equals(workInformationBean.getRows().getOutsourceFlag())) {
                if (!"5".equals(workInformationBean.getRows().getNowStat()) && !"10".equals(workInformationBean.getRows().getNowStat())
                        && !"11".equals(workInformationBean.getRows().getNowStat())
                        && ("12".equals(ownerBean.getRows().getEmployee().getRoleId()) || "10".equals(ownerBean.getRows().getEmployee().getRoleId()))) {
                    if ("0".equals(workInformationBean.getRows().getNowStat()) || "18".equals(workInformationBean.getRows().getNowStat())) {
                        //指派给
                        isNowState = true;
                    }
                    powerSet.add(POWER_ZHIPAIGEI);
                }
                if ("3".equals(workInformationBean.getRows().getNowStat()) &&
                        ownerBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())) {
                    //接单  转回
                    isNowState = true;
                    powerSet.add(POWER_JIEDAN);
                    powerSet.add(POWER_ZHUANHUI);
                }
                if ("1".equals(workInformationBean.getRows().getTreatment())) {
                    if ("4".equals(workInformationBean.getRows().getNowStat())
                            || "16".equals(workInformationBean.getRows().getNowStat())
                            || "17".equals(workInformationBean.getRows().getNowStat())) {
                        if (ownerBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())) {
                            // 转回
                            isNowState = true;
                            powerSet.add(POWER_ZHUANHUI);
                        }
                        if (ownerBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())
                                || ("12".equals(ownerBean.getRows().getEmployee().getRoleId())
                                || "10".equals(ownerBean.getRows().getEmployee().getRoleId()))) {
                            // 挂起
                            powerSet.add(POWER_GUAQI);
                        }
                        if (ownerBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())
                                && "4".equals(workInformationBean.getRows().getNowStat())) {
                            // 非现场  出发
                            powerSet.add(POWER_FEIXIANCHANG);
                            powerSet.add(POWER_CHUFA);
                        } else if (ownerBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())
                                && "16".equals(workInformationBean.getRows().getNowStat())) {
                            // 到达
                            powerSet.add(POWER_DAODA);
                        } else if (ownerBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())
                                && "17".equals(workInformationBean.getRows().getNowStat())) {
                            if (!TextUtils.isEmpty(workInformationBean.getRows().getHardWareIds())) {
                                // 备件申请
                                powerSet.add(POWER_BEIJIANSHENQING);
                            }
                            // 处理
                            powerSet.add(POWER_CHULI);
                        }
                    }
                } else {
                    if ("4".equals(workInformationBean.getRows().getNowStat())) {
                        if (ownerBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())) {
                            // 转回
                            isNowState = true;
                            powerSet.add(POWER_ZHUANHUI);
                        }
                        if (ownerBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())
                                || ("12".equals(ownerBean.getRows().getEmployee().getRoleId())
                                || "10".equals(ownerBean.getRows().getEmployee().getRoleId()))) {
                            // 挂起
                            isNowState = true;
                            powerSet.add(POWER_GUAQI);
                        }
                        if (ownerBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())) {
                            //去现场
                            isNowState = true;
                            powerSet.add(POWER_QUXIANCHANG);
                            if (!TextUtils.isEmpty(workInformationBean.getRows().getHardWareIds())) {
                                // 备件申请
                                powerSet.add(POWER_BEIJIANSHENQING);
                            }
                            // 处理
                            powerSet.add(POWER_CHULI);
                        }
                    }
                }
                if ("7".equals(workInformationBean.getRows().getNowStat())
                        && (ownerBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())
                        || ("12".equals(ownerBean.getRows().getEmployee().getRoleId())
                        || "10".equals(ownerBean.getRows().getEmployee().getRoleId())
                        || "11".equals(ownerBean.getRows().getEmployee().getRoleId())))) {
                    // 启动
                    isNowState = true;
                    powerSet.add(POWER_QIDONG);
                }
            }
            if ("9".equals(workInformationBean.getRows().getNowStat())
                    && ownerBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getSendUser())) {
                // 确认
                isNowState = true;
                powerSet.add(POWER_QUEREN);
            }
            if (("12".equals(ownerBean.getRows().getEmployee().getRoleId()) || "10".equals(ownerBean.getRows().getEmployee().getRoleId()))
                    && !"10".equals(workInformationBean.getRows().getNowStat())
                    && !"5".equals(workInformationBean.getRows().getNowStat())
                    && !"11".equals(workInformationBean.getRows().getNowStat())
                    && "0".equals(workInformationBean.getRows().getOutsourceFlag())) {
                //关闭
                powerSet.add(POWER_GUANBI);
            }
            if (("0".equals(workInformationBean.getRows().getNowStat()) || "18".equals(workInformationBean.getRows().getNowStat()))
                    && ownerBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getSendUser())) {
                //取消
                powerSet.add(POWER_QUXIAO);
            }
            if (!"5".equals(workInformationBean.getRows().getRequestType())
                    && ownerBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getSendUser())
                    && TextUtils.isEmpty(workInformationBean.getRows().getComplainFlag())
                    && !"11".equals(workInformationBean.getRows().getNowStat())) {
                // 投诉
                powerSet.add(POWER_TOUSU);
            }
        } else if ("2".equals(companyType)) {
            if (!"5".equals(workInformationBean.getRows().getNowStat()) && !"10".equals(workInformationBean.getRows().getNowStat())
                    && !"11".equals(workInformationBean.getRows().getNowStat())
                    && ("12".equals(serviceLoginBean.getRows().getEmployee().getRoleId()) || "10".equals(serviceLoginBean.getRows().getEmployee().getRoleId()))) {
                if ("0".equals(workInformationBean.getRows().getNowStat()) || "18".equals(workInformationBean.getRows().getNowStat())) {
                    //指派给
                    isNowState = true;
                }
                powerSet.add(POWER_ZHIPAIGEI);
            }
            if ("3".equals(workInformationBean.getRows().getNowStat()) &&
                    serviceLoginBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())) {
                //接单  转回
                isNowState = true;
                powerSet.add(POWER_JIEDAN);
                powerSet.add(POWER_ZHUANHUI);
            }
            if ("1".equals(workInformationBean.getRows().getTreatment())) {
                if ("4".equals(workInformationBean.getRows().getNowStat())
                        || "16".equals(workInformationBean.getRows().getNowStat())
                        || "17".equals(workInformationBean.getRows().getNowStat())) {
                    if (serviceLoginBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())) {
                        // 转回
                        isNowState = true;
                        powerSet.add(POWER_ZHUANHUI);
                    }
                    if (serviceLoginBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())
                            || ("12".equals(serviceLoginBean.getRows().getEmployee().getRoleId())
                            || "10".equals(serviceLoginBean.getRows().getEmployee().getRoleId()))) {
                        // 挂起
                        powerSet.add(POWER_GUAQI);
                    }
                    if (serviceLoginBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())
                            && "4".equals(workInformationBean.getRows().getNowStat())) {
                        // 非现场  出发
                        powerSet.add(POWER_FEIXIANCHANG);
                        powerSet.add(POWER_CHUFA);
                    } else if (serviceLoginBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())
                            && "16".equals(workInformationBean.getRows().getNowStat())) {
                        // 到达
                        powerSet.add(POWER_DAODA);
                    } else if (serviceLoginBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())
                            && "17".equals(workInformationBean.getRows().getNowStat())) {
                        if (!TextUtils.isEmpty(workInformationBean.getRows().getHardWareIds())
                                && !TextUtils.isEmpty(workInformationBean.getRows().getRelationIds())) {
                            // 备件申请
                            powerSet.add(POWER_BEIJIANSHENQING);
                        }
                        // 处理
                        powerSet.add(POWER_CHULI);
                    }
                }
            } else {
                if ("4".equals(workInformationBean.getRows().getNowStat())) {
                    if (serviceLoginBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())) {
                        // 转回
                        isNowState = true;
                        powerSet.add(POWER_ZHUANHUI);
                    }
                    if (serviceLoginBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())
                            || ("12".equals(serviceLoginBean.getRows().getEmployee().getRoleId())
                            || "10".equals(serviceLoginBean.getRows().getEmployee().getRoleId()))) {
                        // 挂起
                        isNowState = true;
                        powerSet.add(POWER_GUAQI);
                    }
                    if (serviceLoginBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())) {
                        //去现场
                        isNowState = true;
                        powerSet.add(POWER_QUXIANCHANG);
                        if (!TextUtils.isEmpty(workInformationBean.getRows().getHardWareIds())
                                && !TextUtils.isEmpty(workInformationBean.getRows().getRelationIds())) {
                            // 备件申请
                            powerSet.add(POWER_BEIJIANSHENQING);
                        }
                        // 处理
                        powerSet.add(POWER_CHULI);
                    }
                }
            }
            if ("7".equals(workInformationBean.getRows().getNowStat())
                    && (serviceLoginBean.getRows().getEmployeeId().equals(workInformationBean.getRows().getResponseUserId())
                    || ("12".equals(serviceLoginBean.getRows().getEmployee().getRoleId())
                    || "10".equals(serviceLoginBean.getRows().getEmployee().getRoleId())))) {
                // 启动
                isNowState = true;
                powerSet.add(POWER_QIDONG);
            }
            if (("12".equals(serviceLoginBean.getRows().getEmployee().getRoleId()) || "10".equals(serviceLoginBean.getRows().getEmployee().getRoleId()))
                    && !"10".equals(workInformationBean.getRows().getNowStat())
                    && !"5".equals(workInformationBean.getRows().getNowStat())
                    && !"11".equals(workInformationBean.getRows().getNowStat())) {
                //关闭
                powerSet.add(POWER_GUANBI);
            }
        }
        // 判断 是否刷新

        if (powerSet.size() == 0) {
            if (isLook)
                EventBus.getDefault().post(new WorkPageStateRefreseEvent(workInformationBean.getRows().getNowStat(), false));
            rlButton.setVisibility(View.GONE);
        } else {
            if (isLook)
                EventBus.getDefault().post(new WorkPageStateRefreseEvent(workInformationBean.getRows().getNowStat(), isNowState));
            rlButton.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onException(int requestId, String code) {
        showTopWrongMsg(getResources().getString(R.string.net_work_error));
    }

    public static void OpenActivity(Context context, String requestId, String newRequestId, String outsourceFlag) {
        Intent i = new Intent(context, WorkInformationActivity.class);
        if (context instanceof Application) {
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        i.putExtra("requestId", requestId);
        i.putExtra("newRequestId", newRequestId);
        i.putExtra("outsourceFlag", outsourceFlag);
        context.startActivity(i);
    }

    public static void OpenActivity(Context context, String requestId, String newRequestId, String outsourceFlag, boolean isLook) {
        Intent i = new Intent(context, WorkInformationActivity.class);
        if (context instanceof Application) {
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        i.putExtra("requestId", requestId);
        i.putExtra("newRequestId", newRequestId);
        i.putExtra("outsourceFlag", outsourceFlag);
        i.putExtra("isLook", isLook);
        context.startActivity(i);
    }


}
